<template>
  <a-modal
    :width="1000"
    :title="title"
    :height="550"
    :visible="innerVisible"
    @cancel="handleCancel"
    cancelText="关闭"
    :okButtonProps="{ style: { display: 'none' } }"
  >
    <a-alert type="info" showIcon style="margin-bottom: 16px">
      <template slot="message">
        <span>已选择</span>
        <a style="font-weight: 600; padding: 0 4px">{{ selectedRowKeys.length }}</a>
        <span>项</span>
        <template v-if="selectedRowKeys.length > 0">
          <a-divider type="vertical" />
          <a @click="handleClearSelection">清空选择</a>
          <a-divider type="vertical" />
          <a @click="handleRevertBatch">批量还原</a>
          <a-divider type="vertical" />
          <a @click="handleDeleteBatch">批量删除</a>
        </template>
      </template>
    </a-alert>

    <a-table
      ref="table"
      rowKey="id"
      size="middle"
      bordered
      :scroll="{ y: 450 }"
      :columns="columns"
      :loading="loading"
      :dataSource="dataSource"
      :pagination="ipagination"
      :rowSelection="{ selectedRowKeys, onChange: handleTableSelectChange }"
      @change="handleTableChange"
    >
      <!-- 显示头像 -->
      <template slot="avatarslot" slot-scope="text, record">
        <div class="anty-img-wrap">
          <a-avatar shape="square" :src="url.getAvatar(record.avatar)" icon="user" />
        </div>
      </template>

      <span slot="action" slot-scope="text, record">
        <a @click="handleRevert([record.id])"><a-icon type="redo" /> 还原用户</a>
        <a-divider type="vertical" />
        <a @click="handleDelete([record.id])"><a-icon type="delete" /> 彻底删除</a>
      </span>
    </a-table>
  </a-modal>
</template>

<script>
import { deleteAction, getFileAccessHttpUrl, getAction } from '@/api/manage'

export default {
  name: 'UserRecycleBinModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      title: '用户回收站',
      loading: false,
      innerVisible: false,
      selectedRowKeys: [],
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      columns: [
        { title: '#', align: 'center', key: 'rowIndex', width: 80, customRender: (t, r, i) => i + 1 },
        { title: '账号', align: 'center', dataIndex: 'username' },
        { title: '姓名', align: 'center', dataIndex: 'realname' },
        { title: '头像', align: 'center', dataIndex: 'avatar', scopedSlots: { customRender: 'avatarslot' } },
        { title: '部门', align: 'center', dataIndex: 'orgCode' },
        { title: '操作', align: 'center', dataIndex: 'action', width: 200, scopedSlots: { customRender: 'action' } }
      ],
      url: {
        getAvatar: (path) => getFileAccessHttpUrl(`${path}`),
        // 回收站操作，get = 获取列表；put = 取回；delete = 彻底删除
        recycleBin: '/sys/sysUserHist/list',
        putRecycleBin: '/sys/sysUserHist/recoveryBatch',
        deleteRecycleBin: '/sys/sysUserHist/deleteBatch'
      }
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        if (val) {
          this.loadData()
        }
        this.innerVisible = val
      }
    },
    innerVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {

    loadData(arg) {
      if (!this.url.recycleBin) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      const  params = {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize
      }
      getAction(this.url.recycleBin, params).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          this.dataSource = res.result.records || res.result
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0;
          }
        } else {
          this.$message.warning(res.message)
        }
      })
    },

    handleTableChange(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      this.ipagination = pagination
      this.loadData()
    },
    handleOk() {
      this.loadData()
      this.$emit('ok')
    },
    handleCancel() {
      this.innerVisible = false
    },
    // 还原用户
    handleRevert(userIds) {
      this.$confirm({
        title: '恢复用户',
        content: `您确定要恢复这 ${userIds.length} 个用户吗？`,
        centered: true,
        onOk: () => {
          deleteAction(this.url.putRecycleBin, { ids: userIds.join(',') }).then((res) => {
            if (res.success) {
              this.handleOk()
              this.handleClearSelection()
              this.$message.success(`还原 ${userIds.length} 个用户成功！`)
            }
          })
        }
      })
    },
    // 彻底删除用户
    handleDelete(userIds) {
      this.$confirm({
        title: '彻底删除用户',
        content: (<div>
          <p>您确定要彻底删除这 {userIds.length} 个用户吗？</p>
          <p style="color:red;">注意：彻底删除后将无法恢复，请谨慎操作！</p>
        </div>),
        centered: true,
        onOk: () => {
          var that = this
          deleteAction(that.url.deleteRecycleBin, { ids: userIds.join(',') }).then((res) => {
            if (res.success) {
              this.loadData()
              this.handleClearSelection()
              this.$message.success(`彻底删除 ${userIds.length} 个用户成功！`)
            } else {
              that.$message.warning(res.message)
            }
          })
        }
      })
    },
    handleRevertBatch() {
      this.handleRevert(this.selectedRowKeys)
    },
    handleDeleteBatch() {
      this.handleDelete(this.selectedRowKeys)
    },
    handleClearSelection() {
      this.handleTableSelectChange([], [])
    },
    handleTableSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    }
  }
}
</script>